<?php

namespace App\Http\Controllers\V1\Upload;

use App\Models\V1\ApplyDorms;
use App\Models\V1\NewStudent;
use Illuminate\Http\Request;
use App\Http\Requests\V1\ImportDataRequest;
use Maatwebsite\Excel\Facades\Excel;
use App\Events\V1\ImportExportEvent;
use Jenssegers\Agent\Agent;
use Illuminate\Support\Facades\Auth;
use Log;

class DormExcelUploadController extends BaseExcelUploadController
{
    
    /**
     * 导出校服信息汇总数据
     *
     * @param Request $request
     */
    public function exportData(Request $request)
    {
        $clientIP = $request->getClientIp();

        $header = ['姓名', '性别', '考试号', '证件号', '招生目录(大类专业/方向)', '家庭所在地', '申请理由', '申请时间', '修改时间'];
        $custodian = ApplyDorms::all(['exam_code', 'apply_reason', 'address', 'created_at', 'updated_at']);
        $cellDatas = [$header];
        foreach ($custodian as $item) {
            //获取学生基本信息
            $Info = NewStudent::where('exam_code', $item->exam_code)
                    ->first();
            $StudentName = $Info->name;
            $StudentSex = $Info->sex == 1 ? '男' : (($Info->sex == 2) ? '女' : '无');
            $StudentCardNumber = $Info->card_number;
            $StudentDirectory = $Info->enrollment_directory;
            
            $cellData = [
                $StudentName,
                $StudentSex,
                $item->exam_code,
                $StudentCardNumber,
                $StudentDirectory,
                $item->address,
                $item->apply_reason,
                $item->created_at,
                $item->updated_at,
            ];
            array_push($cellDatas, $cellData);
        }

        Excel::create(iconv('UTF-8', 'GBK','宿舍申请汇总'), function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('uniform', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });

            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[宿舍申请汇总]导出文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }
}
